package org.example.java.jvm.monitoring;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadInfo;
import java.lang.management.ThreadMXBean;
import java.util.concurrent.TimeUnit;

/**
 * 死锁问题
 */
public class ThreadDeadLockTest {
  static class SynAddRunnable implements Runnable {
    final Integer a, b;

    public SynAddRunnable(Integer a, Integer b) {
      this.a = a;
      this.b = b;
    }

    @Override
    public void run() {
      synchronized (a) {
        Thread.yield();
        synchronized (b) {
          System.out.println(a + b);
        }
      }
    }
  }

  public static void main(String[] args) throws InterruptedException {
    Integer a = 1, b = 2;
    for (int i = 0; i < 10; i++) {
      new Thread(new SynAddRunnable(a, b)).start();
      new Thread(new SynAddRunnable(b, a)).start();
    }

    TimeUnit.SECONDS.sleep(1);
    ThreadMXBean bean = ManagementFactory.getThreadMXBean();
    for (ThreadInfo info : bean.getThreadInfo(bean.findDeadlockedThreads(), true, true)) {
      System.out.println(info);
    }
  }
}
